package cn.jimmie.lib.qlog.support;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.content.PermissionChecker;

/**
 * Created by <zhangsheng@4399inc.com> on 2018-06-08.
 */
public class AlChecker {
    public static boolean isPermissionGranted(Context ctx, String... permissions) {
        for (String p : permissions) {
            if (!selfPermissionGranted(ctx, p))
                return false;
        }

        return true;
    }

    private static boolean selfPermissionGranted(Context ctx, String permission) {
        boolean ret;
        if (higherAndroidM()) {
            if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M) {
                ret = ctx.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
            } else {
                ret = PermissionChecker.checkSelfPermission(ctx, permission) == PermissionChecker.PERMISSION_GRANTED;
            }
        } else {
            ret = checkPermissionRegistered(ctx, permission);
        }
        return ret;
    }

    private static boolean checkPermissionRegistered(Context context, String permission) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_PERMISSIONS);
            String[] permissions = packageInfo.requestedPermissions;
            for (String p : permissions)
                if (permission.equals(p))
                    return true;

        } catch (PackageManager.NameNotFoundException ignored) {
        }
        return false;
    }

    private static boolean higherAndroidM() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }
}
